package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;


public class JiaozhunActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener,DataProcessorManagerRight.DataUpdateListener{
    private static final String TAG = "JiaozhunActivity";
    private BluetoothService bluetoothService;
    private boolean isBound = false;
    private Button btn;
    private DataProcessorManager processorManager;
    private DataProcessorManagerRight processorManagerRight;
    private String deviceId;
    private LinearLayout loadingOverlay ;
//    private LinkedBlockingQueue<byte[]> dataQueue = new LinkedBlockingQueue<>(5000);
//    private LinkedBlockingQueue<byte[]> dataQueue2 = new LinkedBlockingQueue<>(5000);
//private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
    private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Boolean isJiaozhun1=false;
    private Boolean isJiaozhun2=false;
    private Integer handDir=0;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            processorManager=null;
            processorManagerRight=null;
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                    processorManager.temp = handDir;
                    processorManager.setDeviceMac(deviceId.replace(":", ""));
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    Log.d("ServiceTest", "onServiceConnected: dataQueue2=" + dataQueue2.size());

                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                    processorManager.temp = handDir;
                    processorManager.setDeviceMac(deviceId.replace(":", ""));
                }
            }
            else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.temp = 1;
                processorManager.setDeviceMac(deviceMacLeft.replace(":", ""));
                processorManagerRight=DataProcessorManagerRight.getInstance(dataQueue2);
                processorManagerRight.temp = 2;
                processorManagerRight.setDeviceMac(deviceMacRight.replace(":", ""));
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_jiaozhun);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("校准动作");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        handDir = sp.getInt("handDirection",0);
        System.out.println("ffffffffffffffffffhandDir:"+handDir);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(JiaozhunActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(JiaozhunActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }
//            if (deviceId == "" || deviceId.isEmpty()) {
//                Toast.makeText(JiaozhunActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(JiaozhunActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(JiaozhunActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
            System.out.println("magcor----deviceMacLeft:"+deviceMacLeft);
            System.out.println("magcor----deviceMacRight:"+deviceMacRight);
//            if (deviceMacLeft == null || deviceMacLeft.isEmpty() || deviceMacRight == null || deviceMacRight.isEmpty()) {
//                Toast.makeText(JiaozhunActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }

        loadingOverlay  = findViewById(R.id.loadingOverlay);

        btn = findViewById(R.id.jiaozhunBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(conDeviceNum==1) {
                    if(handDir==1){
                        if(isLeftDeviceReceived==false){
                            Toast.makeText(JiaozhunActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    if(handDir==2){
                        if (isRightDeviceReceived == false) {
                            Toast.makeText(JiaozhunActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                        System.out.println("jiaozhun-time0:"+System.currentTimeMillis());
                        loadingOverlay.setVisibility(View.VISIBLE);
                        processorManager.setDataUpdateListener(JiaozhunActivity.this);
                        processorManager.startProcessing();
                        processorManager.setProcessingFunction(ProcessingFunction.Blank);
                        processorManager.setzero();
                    System.out.println("jiaozhun-time1:"+System.currentTimeMillis());

                    processorManager.setProcessingFunction(ProcessingFunction.DuizhiBias);
                    System.out.println("jiaozhun-time2:"+System.currentTimeMillis());

                    Toast.makeText(JiaozhunActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
                }else {
                    if(isLeftDeviceReceived==false){
                        Toast.makeText(JiaozhunActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else if(isRightDeviceReceived==false){
                        Toast.makeText(JiaozhunActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else {
                        loadingOverlay.setVisibility(View.VISIBLE);
                        processorManager.setDataUpdateListener(JiaozhunActivity.this);
                        processorManager.startProcessing();
                        processorManager.setProcessingFunction(ProcessingFunction.Blank);
                        processorManager.setzero();
                        processorManager.setProcessingFunction(ProcessingFunction.DuizhiBias);

                        processorManagerRight.setDataUpdateListener(JiaozhunActivity.this);
                        processorManagerRight.startProcessing();
                        processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
                        processorManagerRight.setzero();
                        processorManagerRight.setProcessingFunction(ProcessingFunction.DuizhiBias);

                        Toast.makeText(JiaozhunActivity.this, "开始测试", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("jiaozhun-onDataProcessed-Flag:" + data.getValue());
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if (flag.equals("duizhibias")) {
            isJiaozhun1=true;
            processorManager.stopProcessing();
            if(conDeviceNum==1) {
                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("isJiaozhun", true);
                editor.apply();
                loadingOverlay.setVisibility(View.GONE);
                Toast.makeText(JiaozhunActivity.this, "校准完成", Toast.LENGTH_SHORT).show();
                finish();
            }
            if (conDeviceNum == 2) {
                if (isJiaozhun1 == true && isJiaozhun2 == true) {
                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("isJiaozhun", true);
                    editor.apply();
                    loadingOverlay.setVisibility(View.GONE);
                    Toast.makeText(JiaozhunActivity.this, "校准完成", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }
    @Override
    public void onDataProcessedRight(ProcessedData data){
        String flag = data.getFlag();
        System.out.println("jiaozhun-onDataProcessedRight-Flag:" + data.getValue());
        if(flag.equals("fileNull")){
            Toast.makeText(this,"缺少文件",Toast.LENGTH_SHORT).show();
            return;
        }
        if (flag.equals("duizhibias")) {
            isJiaozhun2 = true;
            processorManagerRight.stopProcessing();
            if (conDeviceNum == 1) {
                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("isJiaozhun", true);
                editor.apply();
                loadingOverlay.setVisibility(View.GONE);
                Toast.makeText(JiaozhunActivity.this, "校准完成", Toast.LENGTH_SHORT).show();
                finish();
            }

            if (conDeviceNum == 2) {
                if (isJiaozhun1 == true && isJiaozhun2 == true) {
                    SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("isJiaozhun", true);
                    editor.apply();
                    loadingOverlay.setVisibility(View.GONE);
                    Toast.makeText(JiaozhunActivity.this, "校准完成", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onStop() {
        super.onStop();
//        if(conDeviceNum==1) {
//            processorManager.setProcessingFunction(ProcessingFunction.Blank);
//        }else {
//            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
//        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(conDeviceNum==1) {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }else {
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            processorManagerRight.setProcessingFunction(ProcessingFunction.Blank);
            processorManagerRight.setzero();
            processorManagerRight.stopProcessing();
        }
    }
}